using System;
using System.Configuration;
using System.Web;

namespace WSKnowledge.WSHelpers.NHibernate
{
	public class UnitOfWorkHttpModule : IHttpModule
	{
		private const string ContextUnitOfWorkKey = "NHibernate.UnitOfWork.Context";
		private static readonly string hbmConfigFile = ConfigurationManager.AppSettings["nhibernate.unit_of_work.http_module"];

		public void Init(HttpApplication context)
		{
			context.BeginRequest += Context_BeginRequest;
			context.EndRequest += Context_EndRequest;
		}

		private void Context_BeginRequest(object sender, EventArgs e)
		{
			var application = (HttpApplication)sender;

			if (!application.Context.Request.Path.Contains(".aspx") ||
			    application.Context.Request.RawUrl.Contains("_TSM_HiddenField_")) return;

			var factory = NHibernateService.Builder.GetSessionFactoryFor(hbmConfigFile);
			application.Context.Items[ContextUnitOfWorkKey] = new UnitOfWork(factory);
		}

		private void Context_EndRequest(object sender, EventArgs e)
		{
			try
			{
				ContextUnitOfWork.Commit();
			}
			catch (Exception)
			{
				//TODO: need to logging here
				throw;
			}
		}

		public void Dispose()
		{
		}

		public static IUnitOfWork ContextUnitOfWork
		{
			get
			{
				if (HttpContext.Current.Items.Contains(ContextUnitOfWorkKey))
					return (IUnitOfWork)HttpContext.Current.Items[ContextUnitOfWorkKey];

				return null;
			}
		}
	}
}
